import axios from 'axios'
import { ElNotification } from 'element-plus'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/stores/user'
import { blobValidate } from '@/utils/validate'

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: '/api',
  // 超时
  timeout: 10000
})

// request拦截器
service.interceptors.request.use(
  config => {
    // admin路径不添加认证头
    if (config.url && config.url.includes('/admin/')) {
      // 对admin路径不添加任何认证头
      delete config.headers['Authorization'];
    } else {
      // 对其他路径添加认证头
      const isToken = (config.headers || {}).isToken === false
      if (getToken() && !isToken) {
        config.headers['Authorization'] = 'Bearer ' + getToken()
      }
      
      // 从localStorage获取用户名，添加到请求头
      const username = localStorage.getItem('username')
      if (username) {
        config.headers['Username'] = username
      }
    }
    
    // 默认设置请求头
    if (!config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/json;charset=utf-8'
    }
    
    // 输出请求日志
    console.log('Request URL:', config.url)
    console.log('Request Method:', config.method)
    console.log('Request Headers:', config.headers)
    console.log('Request Data:', config.data)
    
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 输出响应日志
    console.log('Response Status:', response.status)
    console.log('Response Data:', response.data)
    
    const res = response.data
    // 如果返回数据不是200则视为错误
    if (res.code !== 200) {
      ElNotification({
        message: res.message || '系统错误',
        type: 'error',
        duration: 5 * 1000
      })

      // 401: 未登录或token过期 - 暂时禁用自动登出
      if (res.code === 401) {
        console.warn('收到401错误，但不自动登出')
        // 以下代码被注释掉，0不再自动登出
        const userStore = useUserStore()
        userStore.logout().then(() => {
          location.reload()
        })
      }
      return Promise.reject(new Error(res.message || '系统错误'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    if (error.response) {
      console.log('Error Response:', error.response.data)
      console.log('Error Status:', error.response.status)
      console.log('Error Headers:', error.response.headers)
    }
    
    let { message } = error
    if (message === "Network Error") {
      message = "后端接口连接异常"
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时"
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substring(message.length - 3) + "异常"
    }
    ElNotification({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 通用下载方法
export function download(url, params, filename) {
  return service.post(url, params, {
    transformRequest: [(params) => { return JSON.stringify(params) }],
    headers: {
      'Content-Type': 'application/json'
    },
    responseType: 'blob'
  }).then(async (data) => {
    const isLogin = await blobValidate(data)
    if (isLogin) {
      const blob = new Blob([data])
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = filename
      link.click()
      window.URL.revokeObjectURL(link.href)
    } else {
      ElNotification({
        message: '下载文件失败',
        type: 'error',
        duration: 5 * 1000
      })
    }
  }).catch((r) => {
    console.error(r)
  })
}

export default service 